package com.lanou.mynews.news;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.lanou.mynews.R;
import com.lanou.mynews.dao.Person;
import com.lanou.mynews.main.InitApplication;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by dllo on 16/1/8.
 */
public class NewsFragment extends android.support.v4.app.Fragment implements AdapterView.OnItemClickListener {
    private ListView listView;
    private NewsAdapter adapter;
    private List<NewEty.T1348647909107Entity> datas;
    private RequestQueue requestQueue;
    //轮播图

    private String[] titles;
    private ArrayList<View> dots;
    private TextView title;
    private ViewPager mViewPager;//定义一个可以左右滑动的viewpager组件
    private WheelAdapter wheelAdapter;
    private int maxItem = 3; //最大可用图片数目
    private ScheduledExecutorService scheduledExecutorService;
    private ArrayList<ImageView> images;
    //下拉刷新
    SwipeRefreshLayout swipeRefreshLayout;
    String getUrl = "http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html?from=toutiao&size=20&passport=&devId=aXcR0XjnwZWYBFEsCpb%2BiA%3D%3D&lat=9LJ8TmdGBvc2LbBZWwEafA%3D%3D&lon=1BQv9Y5IVN1aORTkfZUEBw%3D%3D&version=5.4.6&net=wifi&ts=1452133871&sign=p1iT9OH0DjNsYDjwv9FDXHg6%2FjAUDOzdrqPTTvN4uCJ48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=QQ_news";
    String shareURL = "http://3g.163.com/touch/article.html?channel=tuijian&docid=";
    /**
     * 切图片用的handler
     */
    private Handler handler = null;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news,
                null);
        View view1 = inflater.cloneInContext(getActivity()).inflate(R.layout.news_wheel, null);

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);

        listView = (ListView) view.findViewById(R.id.listview);
        listView.setOnItemClickListener(this);
        listView.addHeaderView(view1);


        //上拉加载------------------------------------
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                switch (i) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE://当不迁移转变时
                        //断定迁移转变到底部
                        if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {

                            StringRequest request = new StringRequest(getUrl, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    if (response != null) {
                                        Gson gson = new Gson();
                                        NewEty newEty = gson.fromJson(response, NewEty.class);
                                        if (newEty != null && newEty.getT1348647909107() != null) {
                                            Toast.makeText(getActivity(), "加载了", Toast.LENGTH_SHORT).show();
                                            List<NewEty.T1348647909107Entity> a = newEty.getT1348647909107();
                                            datas.addAll(a);
                                            adapter.refreshData(datas);

                                        }
                                    }


                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {

                                }
                            });
                            requestQueue.add(request);
                        }
                        break;

                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getActivity(), "" + datas.get(i-1).getDocid(), Toast.LENGTH_SHORT).show();
                ShareSDK.initSDK(getActivity());
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle(datas.get(i-1).getTitle());
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl(shareURL+datas.get(i-1).getDocid());
                // text是分享文本，所有平台都需要这个字段
                oks.setText((datas.get(i-1).getTitle()+":"+shareURL+datas.get(i-1).getDocid()));
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//                oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                // url仅在微信（包括好友和朋友圈）中使用
//                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl(shareURL+datas.get(i-1).getDocid());
                // 启动分享GUI
                oks.show(getActivity());
                return true;
            }
        });


        //下拉刷新
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light, android.R.color.holo_orange_light, android.R.color.holo_orange_light, android.R.color.holo_orange_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "刷新完成", Toast.LENGTH_SHORT).show();
                        getData();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 3000);
            }
        });


        //显示的点
        dots = new ArrayList<View>();
        dots.add(view1.findViewById(R.id.dot_0));
        dots.add(view1.findViewById(R.id.dot_1));
        dots.add(view1.findViewById(R.id.dot_2));
        dots.add(view1.findViewById(R.id.dot_3));
        title = (TextView) view1.findViewById(R.id.title);
        mViewPager = (ViewPager) view1.findViewById(R.id.vp);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                //设置当前页面
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);//直接当前页+1，就是这么直接
                return false;
            }
        });

        return view;
    }


    @Override
    /**父activity创建完成后...*/
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestQueue = Volley.newRequestQueue(getActivity());
        getData();

    }

    /**
     * 获取轮播图数据
     * 你要准备N+2张图片和文字
     */
    private void getData() {

        System.out.println(getUrl);
        StringRequest request = new StringRequest(getUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    NewEty newEty = gson.fromJson(response, NewEty.class);
                    if (newEty != null && newEty.getT1348647909107() != null) {
                        datas = newEty.getT1348647909107();

                        adapter = new NewsAdapter(datas, getActivity());
                        listView.setAdapter(adapter);


                        //图片标题，准备N+2个
                        titles = new String[]{
                                datas.get(0).getAds().get(3).getTitle(),

                                datas.get(0).getAds().get(0).getTitle(),
                                datas.get(0).getAds().get(1).getTitle(),
                                datas.get(0).getAds().get(2).getTitle(),
                                datas.get(0).getAds().get(3).getTitle(),

                                datas.get(0).getAds().get(0).getTitle(),
                        };
                        maxItem = 3;//实际可用图片，同时也是它的位置
                        //显示的图片
                        images = new ArrayList<ImageView>();
                        requestQueue = Volley.newRequestQueue(getActivity());
                        for (int i = 0; i < titles.length; i++) {
                            //Volley和ImageLoader的加载图片使用组合..
                            //自由度高那么一些。还是picasso简单。。
                            String url;
                            //
                            if (i == 0) {
                                url = datas.get(0).getAds().get(maxItem).getImgsrc();//首
                            } else if (i == titles.length - 1) {
                                url = datas.get(0).getAds().get(0).getImgsrc();//尾
                            } else {
                                url = datas.get(0).getAds().get(i - 1).getImgsrc();//其他图片地址
                            }


                            NetworkImageView imageView = new NetworkImageView(getActivity());//volley用的图片处理..
                            imageView.setDefaultImageResId(R.drawable.loading);
                            imageView.setErrorImageResId(R.drawable.loading);
                            final ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
                                @Override
                                public Bitmap getBitmap(String url) {
                                    return null;
                                }

                                @Override
                                public void putBitmap(String url, Bitmap bitmap) {
                                }
                            });
                            imageView.setImageUrl(url, imageLoader);
                            images.add(imageView);
                        }
                        //之前放循环里不出毛病都是万幸
                        title.setText(titles[1]);
                        mViewPager.setOffscreenPageLimit(maxItem + 3);//重载限制，为啥+3自己想
                        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                            @Override
                            public void onPageSelected(int position) {
                                for (int i = 0; i < dots.size(); i++) {//直接全重新赋值，简单粗暴
                                    dots.get(i).setBackgroundColor(getResources().getColor(R.color.tabBarColor));
                                }
                                dots.get(getIndex(position)).setBackgroundResource(R.color.tabBackGroundColor);
                                title.setText(titles[position]);
                                if (position != getIndex(position) + 1) {//检查当前页面的位置，因为返回数组位置。。需要+1
                                    mViewPager.setCurrentItem(getIndex(position) + 1, true);
                                }
                            }

                            @Override
                            public void onPageScrolled(int arg0, float arg1, int arg2) {

                            }

                            @Override
                            public void onPageScrollStateChanged(int arg0) {

                            }
                        });
                        wheelAdapter = new WheelAdapter();
                        mViewPager.setAdapter(wheelAdapter);//绑定适配器
                        mViewPager.setCurrentItem(1);//摆正位置


                    }
                } else {
                    Toast.makeText(getActivity(), "获取信息失败", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(request);

    }

    //跳转 到 内容------------------
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), NewContent.class);
        intent.putExtra("a", datas.get(position - 1).getDocid());
        startActivity(intent);


    }


    /**
     * 轮播图适配器
     * 这就一空壳。。就是插入VIEW。。
     */
    public class WheelAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));
            return images.get(position);
        }

    }


    @Override
    public void onStart() {
        //连存在判断都不做。。onStart可不只运行一次。。日后可能有祸患
        super.onStart();
        if (scheduledExecutorService == null) {
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();//线程池里添加一个新的任务
            scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 6, 6, TimeUnit.SECONDS);//每隔6秒钟切换一张图片
        }
    }

    @Override
    public void onStop() {

        super.onStop();
    }

    /**
     * 切换图片用Task
     */
    private class ViewPagerTask implements Runnable {

        @Override
        public void run() {
            //更新界面
            handler.obtainMessage().sendToTarget();//第一次见handler这样用。。
        }
    }

    /**
     * 返回图片的实际位置.网址和排序用
     */
    private int getIndex(int position) {

        if (position == 0) {
            return maxItem;
        }
        if (position == titles.length - 1) {
            return 0;
        }
        return position - 1;
    }


}
